//
//  ContentView.swift
//  Hostool
//
//  Created by Beyoug on 2024/11/7.
//

import SwiftUI

struct ContentView: View {
    @EnvironmentObject private var hostsManager: HostsManager
    @State private var showAlert = false
    @State private var alertMessage = ""

    var body: some View {
        VStack {
            TextEditor(text: $hostsManager.hostsContent)
                .font(.system(.body, design: .monospaced))

            HStack {
                Button("保存") {
                    do {
                        try hostsManager.saveHostsFile()
                        alertMessage = "保存成功"
                        // 重新读取
                        try hostsManager.loadHostsFile()
                    } catch {
                        alertMessage = "保存失败: \(error.localizedDescription)"
                    }
                    showAlert = true
                }
                Button("退出") {
                                    NSApplication.shared.terminate(nil)
                                }
            }
            .padding()
        }
        .alert("提示", isPresented: $showAlert) {
            Button("确定", role: .cancel) {}
        } message: {
            Text(alertMessage)
        }
        .frame(minWidth: 400, minHeight: 300)
        .onAppear {
            do {
                try hostsManager.loadHostsFile()
            } catch {
                alertMessage = "读取失败: \(error.localizedDescription)"
                showAlert = true
            }
        }
    }
}
